﻿using System.IO;

namespace Borg.Logging
{
    public sealed class FileLogger : TextLoggerBase
    {
        private readonly StreamWriter _writer;

        internal FileLogger(string path)
        {
            if (path.Contains("{0}"))
                path = GetSerialNumberedLogfileName(path);

            var directoryName = Path.GetDirectoryName(path);

            if (!string.IsNullOrEmpty(directoryName) && !Directory.Exists(directoryName))
                Directory.CreateDirectory(directoryName);

            _writer = new StreamWriter(path);
        }

        public override void Init(Runtime runtime)
        {
            base.Init(runtime);
            Log(new LogArgs(LogType.Info, this, "{0}", new object[] { Runtime.VersionInfo }));
        }

        public override void Dispose()
        {
            try { _writer.Close(); }
            catch { }

            base.Dispose();
        }

        private static string GetSerialNumberedLogfileName(string logfile)
        {
            var ser = 0;
            string path;

            do
            {
                ++ser;
                path = string.Format(logfile, ser);
            }
            while (File.Exists(path) && ser < int.MaxValue);

            return path;
        }

        public override void Log(LogArgs args)
        {
            switch (args.Type)
            {
                case LogType.Warning:
                    _writer.WriteLine("\n--WARNING");
                    break;
                
                case LogType.Error:
                    _writer.WriteLine("\n--ERROR");
                    break;
            }

            _writer.WriteLine(args.Message);
            _writer.Flush();
        }
    }
}
